package cn.tedu.micro.demo.all.service.impl;

import cn.tedu.micro.demo.all.mapper.CartMapper;
import cn.tedu.micro.demo.all.mapper.OrderMapper;
import cn.tedu.micro.demo.all.mapper.StockMapper;
import cn.tedu.micro.demo.all.service.OrderService;
import cn.tedu.micro.demo.common.pojo.po.CartPO;
import cn.tedu.micro.demo.common.pojo.po.OrderPO;
import cn.tedu.micro.demo.common.pojo.po.StockPO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StockMapper stockMapper;

    @Override
    public Boolean submitOrder(Integer userId, String productCode, Integer count) {
        // 1. 扣减库存
        UpdateWrapper<StockPO> updateWrapper = new UpdateWrapper<>();  // 创建更新条件对象
        updateWrapper.setSql("stock = stock-" + count);
        updateWrapper.eq("product_code", productCode);
        int update = stockMapper.update(null, updateWrapper);  // PO类传null，使用对象的非空属性拼接set
        // 1.1 判断是否扣减库存成功，失败则返回false并退出，反之生成订单
        if(update==0){
            return false;
        }
        // 2. 生成订单
        OrderPO order = new OrderPO();
        order.setUserId(userId);
        order.setProductCode(productCode);
        order.setCount(count);
        order.setOrderNo(UUID.randomUUID().toString());
        orderMapper.insert(order);
        // 3. 删除购物车
        QueryWrapper<CartPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("product_code", productCode);
        cartMapper.delete(queryWrapper);

        return true;
    }
}
